package com.pig4cloud.pigx.robot.calculation;

import com.alibaba.fastjson.JSONObject;
import com.mongodb.client.result.UpdateResult;
import com.pig4cloud.pigx.contract.mongo.entity.ContractSymbolMongo;
import com.pig4cloud.pigx.robot.rabbitmq.MQConstant;
import com.pig4cloud.pigx.robot.ws.collect.FetchManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Map;

@Slf4j
@Component
public class LastPrice {
	@Autowired
	private MongoTemplate mongoTemplate;
	@Autowired
	private RabbitTemplate rabbitTemplate;
	@Autowired
	private RedisTemplate redis;

	@RabbitListener(queues = MQConstant.QUEUE_ROBOT_CALC_LAST_PRICE)
	@RabbitHandler
	public void process(String msg) {
		if(FetchManager.robotConfigList == null ){
			return;
		}
		FetchManager.robotConfigList.forEach(item->{
			String symbol = item.getSymbolName();
			BigDecimal sumPrice = new BigDecimal("0");
			int count = 0 ;
			String source_from = "";

			BigDecimal newPrice = new BigDecimal("0");
			try{

				for(int i = 0; i < FetchManager.EXCHANGES.length; i++){
					try{
						Map<String,String> binance =redis.opsForHash().entries("robot_"+FetchManager.EXCHANGES[i]);
						String key = "robot_"+FetchManager.EXCHANGES[i]+"_lastprice_"+symbol;
						if(binance.get(key) != null){
							BigDecimal price = new BigDecimal(binance.get(key).split("_")[0]);
							long ts = Long.valueOf(binance.get(key).split("_")[1]);


							long expire = System.currentTimeMillis()-ts;

							if(expire < FetchManager.expire_millisecond){
								count++;
								sumPrice = sumPrice.add(price);
								source_from = source_from+","+FetchManager.EXCHANGES[i];
							}else {
								log.info("calc last price expire time :"+expire+" exchange:"+FetchManager.EXCHANGES[i] +" Symbol:"+symbol);
							}
						}
					}catch (Exception cx){
						//log.error("calculation index price error"+cx.getMessage());
					}

				}

				if(sumPrice.compareTo(BigDecimal.ZERO) >0 && count > 0){
					newPrice = sumPrice
							.divide(new BigDecimal(count),8, RoundingMode.HALF_UP)
							.setScale(item.getTokenCurAccuracy(),BigDecimal.ROUND_HALF_UP)
							.stripTrailingZeros()
					;

				//	log.info("calc last price  "+symbol+":"+newPrice.toString() + "  ---------- source from :"+source_from);
					// 修改内容
					Update update = Update.update("lastPrice",newPrice );
					// 查询条件
					Criteria criteria = Criteria
							.where("name").is(symbol);

					UpdateResult updateResult = mongoTemplate.updateFirst(new Query(criteria), update, ContractSymbolMongo.class);


					/**************************更新 redis ************************************/
					String redis_key  = symbol+"_last_price";
					redis.opsForValue().set(redis_key,newPrice);

					/**************************发送更新消息队列 ************************************/
//					JSONObject sendMsgObj = new JSONObject();
//					sendMsgObj.put(redis_key,newPrice);
//					rabbitTemplate.convertAndSend(MQConstant.EXCHANGE_FANOUT_ROBOT_LAST_PRICE,"",sendMsgObj);
				}else{
					log.info("no calc last price "+symbol);
				}

			}catch (Exception ex){
				log.error("calculation last price error"+ex.getMessage());
			}


		});




	}
}
